﻿<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Calendario extends Controller_Restrito_Template {

	private function first_last_day($month, $year)
	{
		empty($month) and $month = date('n'); // Current month
		empty($year)  and $year  = date('Y'); // Current year

		// Set the month and year
		$month = (int) $month;
		$year  = (int) $year;
		
		$period['start'] = mktime(0, 0, 0, $month, 1, $year);
		$period['end'] = mktime(23, 59, 59, $month, date('t', mktime(1,0,0, $month, 1, $year)), $year);
		
		return $period;
	}
	
	public function action_index()
	{
		$calendar = new Calendar(Arr::get($_GET, 'month', date('m')), Arr::get($_GET, 'year', date('Y')));
		
		//gera dia inicial e final do mês
		$periodo = $this->first_last_day(
			Arr::get($_GET, 'month', date('m')),
			Arr::get($_GET, 'year', date('Y'))
		);
		//pega os periodos no banco de dados
		$periodos = ORM::factory('periodo')
			->where('inicio', '>=', $periodo['start'])
			->and_where('fim', '<=', $periodo['end'])
			->order_by('inicio')
			->find_all();
		//passa os periodos para o calendário
		foreach($periodos as $periodo):
			$calendar->attach(
				$calendar->event()
				->condition('timestamp', $periodo->inicio)
				->output(
					html::anchor(
						'reserva/ver/'.$periodo->reserva->id,
						date('H:i', $periodo->inicio).' às '. date('H:i', $periodo->fim).
						'<BR>'.
						$periodo->reserva->responsavel->nome,
						array('title' => 'Atividade: '.$periodo->reserva->atividade)))
			);
		endforeach;
		
		$view = new View('calendario/index');
		$view->calendario = $calendar->render();
		$view->periodos = $periodos;
		
		$this->template->body = $view;
	}
	
	public function action_dia()
	{
		$data = $this->request->param('id');
		list($dia, $mes, $ano) = explode('-', $data);
		
		$periodos = ORM::factory('periodo')
			->where('inicio', '>=', mktime(0, 0, 0, $mes, $dia, $ano))
			->and_where('fim', '<=', mktime(23, 59, 59, $mes, $dia, $ano))
			->order_by('inicio')
			->find_all();
		
		$view = new View('calendario/dia');
		$view->data = str_replace('-', '/', $data);
		$view->periodos = $periodos;
		
		$this->template->body = $view;
	}
	
	public function action_relatorio()
	{
		//view que gera o PDF
		$pdf = View_PDF::factory('calendario/relatorio');
		//gera dia inicial e final do mês
		$periodo = $this->first_last_day(
			Arr::get($_GET, 'month', date('m')),
			Arr::get($_GET, 'year', date('Y'))
		);
		//pega os periodos no banco de dados
		$periodos = ORM::factory('periodo')
			->where('inicio', '>=', $periodo['start'])
			->and_where('fim', '<=', $periodo['end'])
			->order_by('inicio')
			->find_all();
		
		$pdf->periodo = $periodo;
		$pdf->periodos = $periodos;
		
		$this->auto_render = FALSE;
		$this->response->body($pdf->render());
		$this->response->send_file(TRUE, date('YmdHis').'auditorio-relatorio-calendario.pdf', array('inline' => TRUE));
	}
	
} // End Calendario
